package com.woniu.shiro_config;

import com.woniu.entity.RbacManager;
import com.woniu.entity.RbacRole;
import com.woniu.service.RbacManagerService;
import com.woniu.service.RbacPermService;
import com.woniu.service.RbacRoleService;
import com.woniu.utils.JWTUtils;
import com.woniu.utils.MyJsonWebToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

/**
 * @author Rain
 * @Description :处理MyJsonWebToken
 * @date 2022/09/06 11:34
 */
@Configuration
public class MyJWTRealm extends AuthorizingRealm {
    private final String REALM_NAME = "MyJWTRealm";

    @Autowired
    RbacManagerService rbacManagerService;

    @Autowired
    RbacRoleService rbacRoleService;

    @Autowired
    RbacPermService rbacPermService;

    public boolean supports(AuthenticationToken token) {
        return token instanceof MyJsonWebToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = authenticationToken.getCredentials() +"";
        String username = JWTUtils.getUsername(token);
        if (username == null){
            throw new AuthenticationException("token中无用户信息");
        }

        //查出密码防止密码更改
        RbacManager rm = rbacManagerService.findOneByName(username);
        try {
            //校验token
            JWTUtils.verify(token,rm.getAccount(),rm.getPassword());
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage());
        }
        //传给授权方法
        return new SimpleAuthenticationInfo(username,token,REALM_NAME);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从token中取出username
        String username = principalCollection.getPrimaryPrincipal()+"";
        //从数据库取出角色信息封装成set
        Set<String> rbacRoles= rbacRoleService.findOneByName(username);
        //将roles通过构造方法封装进SimpleAuthorizationInfo
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo(rbacRoles);

        //从数据库取出权限信息封装成set
        Set<String> rbacPerms = rbacPermService.findPermBySetRoles(username);
        //同上
        sai.setStringPermissions(rbacPerms);
        return sai;
    }
}
